package controllers

import (
	"backend/common"
	"backend/models"
	"net/http"

	"github.com/gin-gonic/gin"
)

func setCookie(ctx *gin.Context, email string) {
	db := common.GetDB()
	var user models.User
	db.Where("email = ?", email).First(&user)

	// 设置 Cookie
	ctx.SetCookie("userid", email, 360000, "/", "", false, true)
	ctx.SetCookie("usertoken", user.PasswordHash, 360000, "/", "", false, true)
}

func removeCookie(ctx *gin.Context) {
	ctx.SetCookie("userid", "", 0, "/", "", false, true)
	ctx.SetCookie("usertoken", "", 0, "/", "", false, true)
}

func checkCookie(userid string, token string) bool {
	// 检查对应的表项存不存在
	db := common.GetDB()
	var user models.User
	db.Where("email = ?", userid).First(&user)

	if user.ID <= 0 || user.PasswordHash != token {
		return false
	}

	return true
}

func CheckCookies(ctx *gin.Context) {
	println("CheckCookies start")
	// 获取userid cookie
	userid, err := ctx.Cookie("userid")
	if err != nil {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"status":  "error",
			"message": "未登录",
		})
		ctx.Abort()
		return
	}
	usertoken, err := ctx.Cookie("usertoken")
	if err != nil {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"status":  "error",
			"message": "未登录",
		})
		ctx.Abort()
		return
	}

	var user models.User
	db := common.GetDB()
	db.Where("email = ? ", userid).First(&user)
	if user.ID <= 0 || user.PasswordHash != usertoken {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"status":  "error",
			"message": "未登录",
		})
		ctx.Abort()
		return
	}
	return
}

func getUserID(ctx *gin.Context) (uint, error) {
	db := common.GetDB()

	// 获取userid cookie
	userid, err := ctx.Cookie("userid")
	if err != nil {
		return 0, err
	}

	var user models.User
	db.Where("email = ? ", userid).First(&user)

	userID := user.ID

	return userID, nil
}
